package com.sun.channel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelTest {

    public static void main(String[] args) throws Exception {
        //readFile();
        writeFile();
    }

    /**
     * 写数据
     * h会把原来的文件内容清掉后重新写文件
     * @throws Exception
     */
    public static void writeFile() throws Exception {
        //创建FileChannel
        RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\test.txt", "rw");
        FileChannel channel = randomAccessFile.getChannel();
        //创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.clear();
        String newData = "username=zhangsan";
        buffer.put(newData.getBytes());
        buffer.flip();
        while (buffer.hasRemaining()) {
            channel.write(buffer);
        }
        channel.close();
    }

    /**
     * 读取数据
     *
     * @throws Exception
     */
    public static void readFile() throws Exception {
        //创建FileChannel
        RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\test.txt", "rw");
        FileChannel channel = randomAccessFile.getChannel();
        //创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //将数据放到buff中
        int byteRead = channel.read(buffer);
        while (byteRead != -1) {  //-1表示文件的末尾
            System.out.println("读取了：" + byteRead);
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.println((char) buffer.get());
            }
            buffer.clear();
            //从channel中读取数据
            byteRead = channel.read(buffer);
        }
        randomAccessFile.close();
        System.out.println("结束了");
    }
}
